﻿using System;
using System.Windows;
using Caliburn.Micro;
using JY.Common.Extensions;
using JY.Wpf.Core.Events;
using JY.Wpf.Core.Extensions;
using JY.Wpf.Core.Models;
using SD.IOC.Core.Mediators;

namespace JY.Wpf.Core.Tools
{
    /// <summary>
    /// 异常处理帮助类
    /// </summary>
    public class ExceptionHelper : IExceptionHelper
    {
        #region # 异常处理方法——void ExceptionHandling(Exception exception)

        /// <summary>
        /// 异常处理方法
        /// </summary>
        /// <param name="exception">异常对象</param>
        public void ExceptionHandling(Exception exception, System.Action autoLogin = null)
        {
            Application.Current.BeginInvoke(() =>
            {
                Exception innerException = exception.GetInnerException();
                string message = innerException == null ? exception.Message : (innerException.InnerException == null ? innerException.Message : innerException.GetErrorMessage());

                try
                {
                    //记录异常 
                    this.WriteLogToService(exception);
                    message = this.GetServiceErrorMessage(message);
                }
                catch
                {

                }
                if (message.Contains("身份过期，请重新登录！"))
                {
                    //自动登录
                    autoLogin?.Invoke();
                    return;
                }
                if (Application.Current.MainWindow == null)
                {
                    MessageBox.Show(message);
                    Application.Current.Shutdown();
                }
                else
                {
                    ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new WarningMessageEvent(message));
                }

                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new BusyIndicatorEvent(false));
                ResolveMediator.Resolve<IEventAggregator>().PublishOnUIThread(new LoginStatusEvent(false));
            });
        }
        #endregion


        #region # 记录异常到本地——void WriteLogToService(Exception e)
        /// <summary>
        /// 记录异常到本地
        /// </summary>
        public void WriteLogToService(Exception exception)
        {
            try
            {
                string log = $"{AppDomain.CurrentDomain.BaseDirectory}Logs\\ErrorLog_{DateTime.Now.Date:yyyyMMdd}.txt";

                FileExtension.WriteFile(log, "=============================异常日志==================================="
                                             + Environment.NewLine + $"***********************************{DateTime.Now}***********************************"
                                             + Environment.NewLine + $"异常信息：{exception.Message}"
                                             + Environment.NewLine + $"详细信息：{exception}"
                                             + Environment.NewLine + $"***********************************结束***********************************"
                                             + Environment.NewLine, true);
            }
            catch
            {
                // ignored
            }
        }
        #endregion

        #region # 获取服务异常信息——virtual string GetServiceErrorMessage(string message)
        /// <summary>
        /// 获取服务异常信息
        /// </summary>
        /// <param name="message">异常消息</param>
        /// <returns></returns>
        public string GetServiceErrorMessage(string message)
        {
            try
            {
                ServiceErrorModel serviceError = message.JsonToObject<ServiceErrorModel>();
                return $"服务异常：{serviceError.ErrorMessage}";
            }
            catch
            {
                return message;
            }
        }
        #endregion
    }

    /// <summary>
    /// 异常处理帮助类接口
    /// </summary>
    public interface IExceptionHelper
    {
        #region # 异常处理方法——void ExceptionHandling(Exception exception)

        /// <summary>
        /// 异常处理方法
        /// </summary>
        /// <param name="exception">异常对象</param>
        void ExceptionHandling(Exception exception, System.Action autoLogin = null);
        #endregion


        #region # 记录异常到本地——void WriteLogToService(Exception exception)

        /// <summary>
        /// 记录异常到本地
        /// </summary>
        void WriteLogToService(Exception exception);
        #endregion

        #region # 获取服务异常信息——virtual string GetServiceErrorMessage(string message)

        /// <summary>
        /// 获取服务异常信息
        /// </summary>
        /// <param name="message">异常消息</param>
        /// <returns></returns>
        string GetServiceErrorMessage(string message);

        #endregion
    }
}
